package com.xatz.scanner

import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import android.text.Editable
import androidx.appcompat.app.AppCompatActivity
import com.symbol.emdk.barcode.ScannerException
import com.xatz.scanner.bean.ReceiveGoodsBean
import com.xatz.scanner.bean.ResponseBean
import com.xatz.scanner.databinding.ActivityReceiveGoodsBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import timber.log.Timber

/**
 * author: tdq
 * date: 2021/7/21
 * description: 移库收货
 */
class ReceivingGoodsActivity : AppCompatActivity(),
    ScannerManger.OnScannerResultListener {

    private lateinit var mBinding: ActivityReceiveGoodsBinding

    private val mService by lazy {
        ScannerRetrofitClient().getService(
            ScannerService::class.java,
            ScannerService.baseGoodsUrl
        )
    }

    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityReceiveGoodsBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        ScannerManger.init(this)
        ScannerManger.setOnScannerResultListener(this)
        mBinding.btnScan.setOnClickListener {
            ScannerManger.bSoftTriggerSelected = true
            if (ScannerManger.scanner != null) {
                if (ScannerManger.scanner?.isReadPending == true) {
                    try {
                        ScannerManger.scanner?.cancelRead()
                    } catch (e: ScannerException) {
                        Timber.e(e)
                    }
                }
            }
        }

        mBinding.btnScan.setOnClickListener {
            val soCode = mBinding.tvOrder.text.toString()
            val count = mBinding.etCount.text.trim().toString()

            if (soCode.isBlank()) {
                toast("请扫码或输入条码！")
                return@setOnClickListener
            }
            if (count.isBlank()) {
                toast("请输入数量！")
                return@setOnClickListener
            }
            val userAccount =
                getSharedPreferences(Constant.configName, Context.MODE_PRIVATE)
                    .getString(Constant.userAccount, "").toString()
            val bean = ReceiveGoodsBean(soCode, count,userAccount)
            mService.confirmReceipt(bean).enqueue(object : Callback<ResponseBean> {
                override fun onResponse(
                    call: Call<ResponseBean>,
                    response: Response<ResponseBean>
                ) {
                    if (response.isSuccessful) {
                        response.body()?.let { tabStr ->
                            if (tabStr.code == "200") {
                                toast("收货成功")
                                mBinding.tvOrder.text = Editable.Factory.getInstance().newEditable("")
                                mBinding.etCount.text =
                                    Editable.Factory.getInstance().newEditable("")
                            }else if(tabStr.code == "500"){
                                runOnUiThread {
                                    toast(tabStr.message)
                                }
                            }
                        }
                    }
                }

                override fun onFailure(call: Call<ResponseBean>, t: Throwable) {
                    Timber.e(t)
                }

            })
        }
    }

    override fun onScannerResult(data: String?, labelType: String) {
        runOnUiThread {
            data?.let {
                mBinding.tvOrder.text = Editable.Factory.getInstance().newEditable(it)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ScannerManger.onClosed()
    }

    override fun onResume() {
        super.onResume()
        // The application is in foreground
        if (ScannerManger.emdkManager != null) {
            // Acquire the barcode manager resources
            ScannerManger.initBarcodeManager(this)
        }
    }

    override fun onPause() {
        super.onPause()
        // The application is in background
        // Release the barcode manager resources
        ScannerManger.deInitScanner()
        ScannerManger.deInitBarcodeManager()
    }
}